package com.quanyan.comment.service.impl;

import com.quanyan.api.APIResponse;
import com.quanyan.comment.constants.UserCenterConstants;
import com.quanyan.comment.mapper.CommentMapper;
import com.quanyan.comment.mapper.TbCommentMapper;
import com.quanyan.comment.mapper.TbCommentSumMapper;
import com.quanyan.comment.model.po.TbComment;
import com.quanyan.comment.model.po.TbCommentExample;
import com.quanyan.comment.model.po.TbCommentSum;
import com.quanyan.comment.model.po.TbCommentSumExample;
import com.quanyan.comment.reqeust.ReqBaseParam;
import com.quanyan.comment.response.RespCommentAvg;
import com.quanyan.comment.response.RespCommentSum;
import com.quanyan.comment.service.CommentSumService;
import com.quanyan.common.constants.Constants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by Administrator on 2016/7/18.
 */
@Service
public class CommentSumServiceImpl implements CommentSumService {

    private static final Logger logger = LoggerFactory.getLogger(CommentSumServiceImpl.class);

    @Autowired
    private TbCommentSumMapper tbCommentSumMapper;

    @Autowired
    private TbCommentMapper tbCommentMapper;

    @Autowired
    private CommentMapper commentMapper;

    @Override
    public RespCommentSum queryCommentSum(ReqBaseParam reqBaseParam) {
        logger.info("开始获取评论汇总信息：{}",reqBaseParam.toString());
        TbCommentSumExample tbCommentSumExample = new TbCommentSumExample();
        TbCommentSumExample.Criteria criteria = tbCommentSumExample.createCriteria();
        criteria.andSystemCodeEqualTo(reqBaseParam.getSystemCode());
        criteria.andBusinessCodeEqualTo(reqBaseParam.getBusinessCode());
        criteria.andBusinessIdEqualTo(reqBaseParam.getBusinessId());
        criteria.andIsDeleteEqualTo(Constants.IS_DELETE_FALSE);
        List<TbCommentSum> commentSumLst =  tbCommentSumMapper.selectByExample(tbCommentSumExample);

        if(commentSumLst == null || commentSumLst.size() < 1){
            logger.info("未查到评论汇总信息");
            return null;
        }

        TbCommentSum t = commentSumLst.get(0);
        RespCommentSum respCommentSum = new RespCommentSum();
        respCommentSum.setBusinessId(t.getBusinessId());
        respCommentSum.setStarZero(t.getStarZero());
        respCommentSum.setStarOne(t.getStarOne());
        respCommentSum.setStarTwo(t.getStarTwo());
        respCommentSum.setStarThree(t.getStarThree());
        respCommentSum.setStarFour(t.getStarFour());
        respCommentSum.setStarFive(t.getStarFive());
        respCommentSum.setCommentCount(t.getCommentCount());

        if(Constants.CLUB_SYSTEM_CODE.equals(reqBaseParam.getSystemCode())){
             byte commentType = (byte)1;//评论
             TbCommentExample tbCommentExample = new TbCommentExample();
             TbCommentExample.Criteria criteriaTbComment = tbCommentExample.createCriteria();
             criteriaTbComment.andSystemCodeEqualTo(reqBaseParam.getSystemCode());
             criteriaTbComment.andBusinessCodeEqualTo(reqBaseParam.getBusinessCode());
             criteriaTbComment.andCommonParamEqualTo(reqBaseParam.getBusinessId());
             criteriaTbComment.andCommentStatusEqualTo(Constants.IS_DELETE_TRUE);//1有效
             criteriaTbComment.andCommentTypeEqualTo(commentType);
             List <TbComment> lst= tbCommentMapper.selectByExample(tbCommentExample);
             respCommentSum.setClubCommentCount(lst.size());
             Double tmpScore = 0.0;
             for (TbComment tbComment : lst ){
                 tmpScore +=tbComment.getScore();
             }
             respCommentSum.setTotalScore(tmpScore);

        }

        logger.info("结束查询评论汇总信息：{}",respCommentSum.toString());
        return respCommentSum;
    }

    @Override
    public void addCommentSum(ReqBaseParam reqBaseParam,int starScore,int commentType){
        if(reqBaseParam == null)
            return ;
        logger.info("开始增加评论统计信息：{},{}",reqBaseParam.toString(),starScore);
        TbCommentSumExample tbCommentSumExample = new TbCommentSumExample();
        TbCommentSumExample.Criteria criteria = tbCommentSumExample.createCriteria();
        criteria.andSystemCodeEqualTo(reqBaseParam.getSystemCode());
        criteria.andBusinessCodeEqualTo(reqBaseParam.getBusinessCode());
        criteria.andBusinessIdEqualTo(reqBaseParam.getBusinessId());
        criteria.andIsDeleteEqualTo(Constants.IS_DELETE_FALSE);
        List<TbCommentSum> commentSumLst =  tbCommentSumMapper.selectByExample(tbCommentSumExample);
        TbCommentSum tbCommentSum = new TbCommentSum();

        if(commentSumLst != null && commentSumLst.size() > 0){
            tbCommentSum = commentSumLst.get(0);
            if(tbCommentSum.getNoReplayCount() == null)
                tbCommentSum.setNoReplayCount(0);
            logger.info("数据库中已存在改统计,改变值即可");
        }else {
            tbCommentSum.setSystemCode(reqBaseParam.getSystemCode());
            tbCommentSum.setBusinessCode(reqBaseParam.getBusinessCode());
            tbCommentSum.setBusinessId(reqBaseParam.getBusinessId());
            tbCommentSum.setCommonParam(reqBaseParam.getCommonParam());
            tbCommentSum.setCreateTime(new Date());
            tbCommentSum.setCommentCount(0);
            tbCommentSum.setNoReplayCount(0);
            tbCommentSum.setStarZero(0);
            tbCommentSum.setStarOne(0);
            tbCommentSum.setStarTwo(0);
            tbCommentSum.setStarThree(0);
            tbCommentSum.setStarFour(0);
            tbCommentSum.setStarFive(0);
            tbCommentSum.setCommonParam(reqBaseParam.getCommonParam());
            logger.info("数据库未存在，新建");
        }

        tbCommentSum.setUpdateTime(new Date());
        tbCommentSum.setCommentCount(tbCommentSum.getCommentCount().intValue() + 1);//累积所有评论
        if(commentType  == UserCenterConstants.CommentType.COMMENT) {//累加评论数量，不包括回复
            tbCommentSum.setNoReplayCount(tbCommentSum.getNoReplayCount() + 1);
        }
        switch(starScore)
        {
            case 0:
                tbCommentSum.setStarZero(tbCommentSum.getStarZero().intValue() + 1);
                break;
            case 1:
                tbCommentSum.setStarOne(tbCommentSum.getStarOne().intValue() + 1);
                break;
            case 2:
                tbCommentSum.setStarTwo(tbCommentSum.getStarTwo().intValue() + 1);
                break;
            case 3:
                tbCommentSum.setStarThree(tbCommentSum.getStarThree().intValue() + 1);
                break;
            case 4:
                tbCommentSum.setStarFour(tbCommentSum.getStarFour().intValue() + 1);
                break;
            case 5:
                tbCommentSum.setStarFive(tbCommentSum.getStarFive().intValue() + 1);
                break;
        }

        if(commentSumLst != null && commentSumLst.size() > 0)
            tbCommentSumMapper.updateByPrimaryKeySelective(tbCommentSum);
        else
            tbCommentSumMapper.insertSelective(tbCommentSum);
        logger.info("增加评论统计信息完毕");
    }



    @Override
    public void updateCommentSum(ReqBaseParam reqBaseParam){
        TbCommentSumExample tbCommentSumExample = new TbCommentSumExample();
        TbCommentSumExample.Criteria criteria = tbCommentSumExample.createCriteria();
        criteria.andSystemCodeEqualTo(reqBaseParam.getSystemCode());
        criteria.andBusinessCodeEqualTo(reqBaseParam.getBusinessCode());
        criteria.andBusinessIdEqualTo(reqBaseParam.getBusinessId());
        criteria.andIsDeleteEqualTo(Constants.IS_DELETE_FALSE);
        List<TbCommentSum> lst = tbCommentSumMapper.selectByExample(tbCommentSumExample);
        if (lst != null && lst.size() > 0){
            TbCommentSum tbCommentSum = lst.get(0);
            TbCommentSum tbCommentSumUpdate = new TbCommentSum();
            tbCommentSumUpdate.setId(tbCommentSum.getId());
            if (tbCommentSum.getCommentCount().intValue() != 0 )
                tbCommentSumUpdate.setCommentCount(tbCommentSum.getCommentCount() - 1);
            if(tbCommentSum.getNoReplayCount() != null || tbCommentSum.getNoReplayCount() != 0)
                tbCommentSumUpdate.setNoReplayCount(tbCommentSum.getNoReplayCount() - 1);
            tbCommentSumMapper.updateByPrimaryKeySelective(tbCommentSumUpdate);
        }

        
    }

    public List<RespCommentSum> findCommentSum(ReqBaseParam reqBaseParam) {
        logger.info("开始获取评论汇总信息：{}",reqBaseParam.toString());
        TbCommentSumExample tbCommentSumExample = new TbCommentSumExample();
        TbCommentSumExample.Criteria criteria = tbCommentSumExample.createCriteria();
        criteria.andSystemCodeEqualTo(reqBaseParam.getSystemCode());
        criteria.andBusinessCodeEqualTo(reqBaseParam.getBusinessCode());
        criteria.andIsDeleteEqualTo(Constants.IS_DELETE_FALSE);
        List<TbCommentSum> commentSumLst =  tbCommentSumMapper.selectByExample(tbCommentSumExample);
        List<RespCommentSum> result = null;
        if(commentSumLst != null || commentSumLst.size() > 0){
            result = new ArrayList<>();
            List<RespCommentSum> lstClubCommentCount = null;
            if(Constants.CLUB_SYSTEM_CODE.equals(reqBaseParam.getSystemCode()))
                lstClubCommentCount = commentMapper.findCommentSumBySbCode(reqBaseParam);
           for (TbCommentSum t : commentSumLst){
               RespCommentSum respCommentSum = new RespCommentSum();
               respCommentSum.setBusinessId(t.getBusinessId());
               respCommentSum.setStarZero(t.getStarZero());
               respCommentSum.setStarOne(t.getStarOne());
               respCommentSum.setStarTwo(t.getStarTwo());
               respCommentSum.setStarThree(t.getStarThree());
               respCommentSum.setStarFour(t.getStarFour());
               respCommentSum.setStarFive(t.getStarFive());
               respCommentSum.setCommentCount(t.getCommentCount());
               if(lstClubCommentCount != null){
                   for (RespCommentSum r : lstClubCommentCount){
                       if (r.getBusinessId().intValue() == t.getBusinessId().intValue()){
                           respCommentSum.setClubCommentCount(r.getClubCommentCount());
                           respCommentSum.setTotalScore(r.getTotalScore());
                           break;
                       }
                   }
               }
               result.add(respCommentSum);
           }
           logger.info("结束查询评论汇总信息：{}",result.toString());
        }


        return result;
    }


    public APIResponse<List<RespCommentSum>> batchQueryClubCommentSum(ReqBaseParam reqBaseParam){
        try {
            List<RespCommentSum> result = this.findCommentSum(reqBaseParam);
            return APIResponse.returnSuccess(result);
        } catch (Exception e) {
            logger.error("",e);
            return APIResponse.returnFail("系统异常");
        }
    }


    /**
     * 根据达人id 计算 平均值
     * @param reqBaseParam
     */
    public RespCommentAvg getAvgByBusinessId(ReqBaseParam reqBaseParam){
        TbCommentSumExample tbCommentSumExample = new TbCommentSumExample();
        TbCommentSumExample.Criteria criteria = tbCommentSumExample.createCriteria();
        criteria.andSystemCodeEqualTo(reqBaseParam.getSystemCode());
        criteria.andBusinessCodeEqualTo(reqBaseParam.getBusinessCode());
        criteria.andCommonParamEqualTo(reqBaseParam.getCommonParam());
        criteria.andIsDeleteEqualTo(Constants.IS_DELETE_FALSE);

        RespCommentAvg respCommentAvg = new RespCommentAvg();
        List<TbCommentSum> tbCommentSums = tbCommentSumMapper.selectByExample(tbCommentSumExample);
        if (tbCommentSums != null && tbCommentSums.size() > 0 ){

            int  onePeople = 0;
            int  twoPeople = 0;
            int  threePeople = 0;
            int  fourPeople = 0;
            int  fivePeople = 0;

            for (TbCommentSum tbCommentSum : tbCommentSums ){
                onePeople += tbCommentSum.getStarOne();
                twoPeople += tbCommentSum.getStarTwo();
                threePeople += tbCommentSum.getStarThree();
                fourPeople += tbCommentSum.getStarFour();
                fivePeople += tbCommentSum.getStarFive();
            }


            int  onePeopleScore = onePeople * 1;
            int  twoPeopleScore = twoPeople * 2;
            int  threePeopleScore = threePeople * 3;
            int  fourPeopleScore = fourPeople * 4;
            int  fivePeopleScore = fivePeople * 5;

            Integer totalPeople = onePeople + twoPeople + threePeople + fourPeople + fivePeople; //总人数
            Integer totalScore  = onePeopleScore + twoPeopleScore + threePeopleScore + fourPeopleScore + fivePeopleScore; //总分数

            Double avgScore = totalScore.doubleValue() / totalPeople.doubleValue() ;
            respCommentAvg.setTotalPeople(totalPeople);
            respCommentAvg.setTotalScore(totalScore);
            respCommentAvg.setAvgScore(Math.round(avgScore*10)/10.0);
        }
        return respCommentAvg;

    }
}
